package org.tgcms.core.dal.appengine.dao;

import org.tgcms.core.dal.appengine.domain.AppengineAttachment;
import org.tgcms.core.dal.appengine.domain.AppenginePage;
import org.tgcms.core.dal.dao.AttachmentDao;
import org.tgcms.core.dal.dao.DaoException;
import org.tgcms.core.dal.dto.Attachment;
import org.tgcms.core.dal.dto.Page;

import com.google.appengine.api.datastore.Key;

public class AppengineAttachmentDao extends
		AppengineEntityDao<AppengineAttachment, Attachment, Page> implements
		AttachmentDao {

	public AppengineAttachmentDao() {
		super(AppengineAttachment.class, Attachment.class);
	}

	@Override
	protected AppengineAttachment asAppengineEntity(Attachment page)
			throws DaoException {
		// if (page instanceof AppenginePage) {
		// return (AppenginePage) page;
		// }
		// return new AppenginePage(page);
		return null;
	}

	@Override
	public Attachment create(Page page) throws DaoException {
		if (!(page instanceof AppenginePage)) {
			throw new DaoException("Page is not an instance of AppenginePage");
		}
		AppenginePage appenginePage = (AppenginePage) page;
		if (appenginePage.getKey() == null) {
			throw new DaoException("Page is not persisted, key is null");
		}
		Key key = datastore
				.allocateIds(appenginePage.getKey(),
						AppengineAttachment.class.getSimpleName(), 1)
				.iterator().next();
		return new AppengineAttachment(key);
	}

}
